// 判断是否有类名
export const hasClass = function(el: HTMLElement, cls: string): boolean {
  if (!el || !cls) return false
  if (cls.indexOf(' ') !== -1) throw new Error('className should not contain space.')
  if (el.classList) {
    return el.classList.contains(cls)
  } else {
    return (' ' + el.className + ' ').indexOf(' ' + cls + ' ') > -1
  }
}

// 添加类名
export const addClass = function(el: HTMLElement, cls: string) {
  if (!el) return
  let curClass = el.className
  const classes = (cls || '').split(' ')

  for (let i = 0, j = classes.length; i < j; i++) {
    const clsName = classes[i]
    if (!clsName) continue

    if (el.classList) {
      el.classList.add(clsName)
    } else if (!hasClass(el, clsName)) {
      curClass += ' ' + clsName
    }
  }
  if (!el.classList) {
    el.className = curClass
  }
}

// 删除类名
export const removeClass = function(el: HTMLElement, cls: string) {
  if (!el || !cls) return
  const classes = cls.split(' ')
  let curClass = ' ' + el.className + ' '

  for (let i = 0, j = classes.length; i < j; i++) {
    const clsName = classes[i]
    if (!clsName) continue

    if (el.classList) {
      el.classList.remove(clsName)
    } else if (hasClass(el, clsName)) {
      curClass = curClass.replace(' ' + clsName + ' ', ' ')
    }
  }
  if (!el.classList) {
    el.className = curClass.trim()
  }
}

// - 转驼峰
export const camelize = function(attr: string): string {
  // /\-(\w)/g 正则内的 (\w) 是一个捕获，捕获的内容对应后面 function 的 letter
  // 意思是将 匹配到的 -x 结构的 x 转换为大写的 X (x 这里代表任意字母)
  /* eslint-disable no-useless-escape */
  return attr.replace(/\-(\w)/g, function(all: string, letter: string) {
    return letter.toUpperCase()
  })
}

// 获取节点样式
export const getStyle = function(el: any, attr: string) { // 获得样式
  const style = window.getComputedStyle(el, null)
  const camelizeAttr = camelize(attr)
  let result
  if (style) {
    result = style.getPropertyValue(attr)
  } else {
    result = el.currentStyle.getAttribute(camelizeAttr)
  }
  return result || el.style[camelizeAttr]
}

export interface Rect {
  width: number,
  height: number,
}

// 获取大小
export const getSize = function(el: HTMLElement): Rect {
  const cloneEl = (el.cloneNode(true) as HTMLElement)
  cloneEl.style.display = 'block'
  cloneEl.style.position = 'fixed'
  cloneEl.style.visibility = 'hidden'
  cloneEl.style.height = ''
  cloneEl.style.top = '100%'
  cloneEl.style.left = '0'

  document.body.append(cloneEl)

  const callback = function() {
    document.body.removeChild(cloneEl)
  }

  const rect: Rect = {
    width: cloneEl.clientWidth + 0,
    height: cloneEl.clientHeight + 0,
  }

  typeof callback === 'function' && callback()

  return rect
}
